<?php
/**
 * Created by PhpStorm.
 * User: liuxiu
 * Date: 2022/2/28
 * Time: 17:43
 */

namespace business\elasticsearch\services;


use business\elasticsearch\repositories\SubBiddingRepository;
use business\search\models\SearchHotModel;
use business\search\models\SearchRecordModel;
use common\utils\DateTimeUtils;

class SubBiddingService
{
    public function getList($params)
    {

        $condition = $this->constructingCondition($params);
        //高亮处理
        $highlight = [
            'pre_tags'  => ['<em class="_high">'],
            'post_tags' => ['</em>'],
            "fields"    => [
                'title' => new \stdClass(),
            ]
        ];

        $subBiddingRepository = new SubBiddingRepository();
        $from                 = ($params['page'] - 1) * $params['pageSize'];
        $orderBy              = [];
        if (isset($params['release_time_sort']) && $params['release_time_sort'] == 0) {
            $orderBy = [
                'release_time' => SORT_ASC
            ];
        } else {
            $orderBy = [
                'release_time' => SORT_DESC
            ];
        }
        $result = [];
        list($total, $list) = $subBiddingRepository->queryList($condition, [], $from, $params['pageSize'], $highlight, $orderBy);
        if (!empty($list)) {
            foreach ($list as $dv) {
                $tmp = $dv['_source'];
                if (!empty($dv['highlight'])) {
                    foreach ($dv['highlight'] as $key => $value) {
                        $tmp[$key . 'HL'] = isset($value[0]) ? $value[0] : '';
                    }
                } else {
                    $tmp['titleHL'] = $tmp['title'];
                }
                $result['resultSet'][] = $tmp;
            }
        } else {
            $result['resultSet'] = [];
        }
        $result['resultNum'] = $total;
        if ((int)$params['page'] === 1) {
            $this->addSearchRecord($params['keyword'], $params['keyword'], $result["resultNum"], "subsbidding", 'pc');
        }
        return $result;
    }

    private function constructingCondition($params)
    {
        $condition = [];
        if (!empty($params['keyword'])) {
            $condition[]['match']['title']['query'] = $params['keyword'];
        }
        if (!empty($params['province_code'])) {
            $condition[]['match']['province_code'] = $params['province_code'];
        }
        if (!empty($params['stage'])) {
            $condition[]['match']['stage'] = $params['stage'];
        }
        if (!empty($params['source_type'])) {
            $condition[]['match']['source_type'] = $params['source_type'];
        }
        $release_time = [];
        if (!empty($params['release_time_start'])) {
            $params['release_time_start'] = date('Y-m-d H:i:s', strtotime($params['release_time_start']));
            $release_time['gte']          = $params['release_time_start'];
        }
        if (!empty($params['release_time_start_end'])) {
            $params['release_time_start_end'] = date('Y-m-d H:i:s', strtotime($params['release_time_start_end']));
            $release_time['lte']              = $params['release_time_start_end'];
        }
        if (!empty($release_time)) {
            $condition[]['range']['release_time'] = $release_time;
        }
        if (!empty($condition)) {
            $query['bool']['must'] = $condition;
            return $query;
        } else {
            return [];
        }
    }

    /**
     * 保存搜索记录
     * @param $keyword
     * @param $analysisKeyword
     * @param $resultRows
     * @param $searchModule
     * @param $source
     */
    protected function addSearchRecord($keyword, $analysisKeyword, $resultRows, $searchModule, $source)
    {
        if (empty($keyword)) {
            return;
        }
        $searchRecord                  = new SearchRecordModel();
        $searchRecord->userId          = '';
        $searchRecord->userType        = '';
        $searchRecord->keyword         = $keyword;
        $searchRecord->analysisKeyword = $analysisKeyword;
        $searchRecord->resultRows      = $resultRows;
        $searchRecord->searchModule    = $searchModule;
        $searchRecord->source          = $source;
        //$searchRecord->ipAddress = IpAddressUtil::getClientIPAddress();
        $searchRecord->searchDate = DateTimeUtils::date();
        $searchRecord->save();
        // 当搜索结果不存在 ，不记录热门搜索
        if (empty($resultRows)) {
            return;
        }
        /** @var SearchHotModel $searchResult */
        $searchResult = SearchHotModel::find()->where(["searchModule" => $searchModule, "keyword" => $keyword])->one();
        if (empty($searchResult)) {
            $searchHot               = new SearchHotModel();
            $searchHot->searchModule = $searchModule;
            $searchHot->keyword      = $keyword;
            $searchHot->count        = 1;
            $searchHot->save();
        } else {
            $searchResult->count = intval($searchResult->count) + 1;
            $searchResult->update();
        }
    }
}